﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

public partial class print_cert : System.Web.UI.Page
{

    public CertificateData mobjCertificateData
    {
        get
        {
            if (ViewState["mobjCertificateData"] == null)
                ViewState["mobjCertificateData"] = System.Guid.NewGuid().ToString();
            return Session[ViewState["mobjCertificateData"].ToString()] as CertificateData;
        }
        set
        {
            if (ViewState["mobjCertificateData"] == null)
                ViewState["mobjCertificateData"] = System.Guid.NewGuid().ToString();
            Session[ViewState["mobjCertificateData"].ToString()] = value;
        }
    }

    public FinishedExams mobjFinishedExams
    {
        get
        {
            if (ViewState["mobjFinishedExams"] == null)
                ViewState["mobjFinishedExams"] = System.Guid.NewGuid().ToString();
            return Session[ViewState["mobjFinishedExams"].ToString()] as FinishedExams;
        }
        set
        {
            if (ViewState["mobjFinishedExams"] == null)
                ViewState["mobjFinishedExams"] = System.Guid.NewGuid().ToString();
            Session[ViewState["mobjFinishedExams"].ToString()] = value;
        }
    }


    public System.Drawing.Image mobjCertificate
    {
        get
        {
            if (ViewState["mobjCertificate"] == null)
                ViewState["mobjCertificate"] = System.Guid.NewGuid().ToString();
            return Session[ViewState["mobjCertificate"].ToString()] as System.Drawing.Image;
        }
        set
        {
            if (ViewState["mobjCertificate"] == null)
                ViewState["mobjCertificate"] = System.Guid.NewGuid().ToString();
            Session[ViewState["mobjCertificate"].ToString()]  = value;
        }
    }



    public Persons mobjUser
    {
        get
        {
            if (ViewState["mobjUser"] == null)
                ViewState["mobjUser"] = System.Guid.NewGuid().ToString();
            return Session[ViewState["mobjUser"].ToString()] as Persons;
        }
        set
        {
            if (ViewState["mobjUser"] == null)
                ViewState["mobjUser"] = System.Guid.NewGuid().ToString();
            Session[ViewState["mobjUser"].ToString()] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            checkAndCustomizeSecurity();

            buildImage();
        }
    }



    /// <summary>
    /// this function will build the image and set it to main Image
    /// </summary>
    private void buildImage()
    {
        try
        {
            bool bAll = true;


            string strImageName = "Certificate.jpg";
            if (!(Request["without"] == null))
            {
                bAll = false;
            }






            System.Drawing.Image bmNew = System.Drawing.Image.FromFile(Server.MapPath("./CertificateImages/" + strImageName));

            Graphics grNew = Graphics.FromImage(bmNew);



            //loading all images

            if (bAll)
            {
                string ILearnImage = "./CertificateImages/" + mobjCertificateData.IamLearningImage;
                string SecLogo = "./CertificateImages/" + mobjCertificateData.SECImage;

                System.Drawing.Image imgILearn = new System.Drawing.Bitmap(100,100);

                try
                { imgILearn = System.Drawing.Image.FromFile(Server.MapPath(ILearnImage)); }
                catch
                { }
                

                System.Drawing.Image imgSecLogo = new  Bitmap(100,100) ;

                try
                { imgSecLogo =  System.Drawing.Image.FromFile(Server.MapPath(SecLogo)); }
                catch
                { }

                ((Bitmap)imgILearn).SetResolution(151f, 151f);
                imgILearn = GlobalVars.resizeImage(imgILearn, 608, 266, Color.White);

                ((Bitmap)imgSecLogo).SetResolution(151f, 151f);
                imgSecLogo = GlobalVars.resizeImage(imgSecLogo, 608, 240, Color.White);

                grNew.DrawImage(imgILearn, new Point(1107, 0));
                grNew.DrawImage(imgSecLogo, new Point(200, 0));

            }




            drawText(grNew, 20, mobjFinishedExams.objRegisteredCourses.objPersons.getFullName(), 478f, bmNew.Width, Color.FromArgb(0x01, 0x00, 0x7F),FontStyle.Regular);

            if (mobjFinishedExams.objRegisteredCourses.objPersons.ID == "")
            {
                drawBadge(grNew, 20, "Badge No. ", mobjFinishedExams.objRegisteredCourses.objPersons.Badge, 548f, bmNew.Width, Color.FromArgb(0,0,0), Color.FromArgb(0x01,0x00,0x7F));

            }


            drawText(grNew, 20, mobjFinishedExams.objRegisteredCourses.objCourses.CourseNameEN, 698f , bmNew.Width,Color.FromArgb(0x98,0x00,0x01),FontStyle.Italic);



            grNew.DrawString(mobjFinishedExams.CurrentDate.ToString("dd/MM/yyyy"), new Font("Tahoma", 18), new SolidBrush(Color.FromArgb(0x01, 0x00, 0x7F)), new PointF(1216f, 775f));


            drawText(grNew, 14, mobjCertificateData.ManagerPos , 1010f, bmNew.Width, Color.FromArgb(0,0,0),FontStyle.Italic);

            drawText(grNew, 14, mobjCertificateData.ManagerName, 1046f, bmNew.Width, Color.FromArgb(0x10,0x13,0x5a),FontStyle.Italic);






            string Stamp = "./CertificateImages/" + mobjCertificateData.StampImage;
            string Sign = "./CertificateImages/" + mobjCertificateData.SignImage;

            System.Drawing.Image imgStamp = new Bitmap(100, 100);

            try
            { imgStamp = System.Drawing.Image.FromFile(Server.MapPath(Stamp)); }
            catch
            { }

            System.Drawing.Image imgSign = new Bitmap(100, 100);
            try
            { imgSign =  System.Drawing.Image.FromFile(Server.MapPath(Sign)); }
            catch
            { }


            ((Bitmap)imgStamp).SetResolution(151f, 151f);
            imgStamp = GlobalVars.resizeImage(imgStamp, 236, 201, Color.White);

            ((Bitmap)imgSign).SetResolution(151f, 151f);
            imgSign = GlobalVars.resizeImage(imgSign, 423, 155, Color.White);




            if (mobjCertificateData.ShowStamp)
            { grNew.DrawImage(imgStamp, new Point(371, 795)); }
            else
            { grNew.FillRectangle(Brushes.White, new Rectangle(413, 1035, 140, 140)); }



            if (mobjCertificateData.ShowSignature)
            { grNew.DrawImage(imgSign, new Point(1259, 831)); }
            else
            { grNew.FillRectangle(Brushes.White, new Rectangle(1363, 1020, 180, 140)); }

            
            
            
            
            
            
            grNew.Dispose();

            mobjCertificate = bmNew;


            mainImage.Src = "./CertificateWriter.ashx?ID=" + ViewState["mobjCertificate"];
        }

        catch
        {
        }


    }


   /// <summary>
   /// this function will draw a text centered in a place on the image by a width
   /// </summary>
   /// <param name="grNew">the graphics to draw</param>
   /// <param name="fontSize">the font size</param>
   /// <param name="text">the text to draw</param>
   /// <param name="y">the y position (no change)</param>
   /// <param name="width">the width to get x by</param>
   /// <param name="cr">this is the color of text to write</param>
    private void drawText(Graphics grNew, int fontSize, string text, float y, float width,Color cr,FontStyle fs)
    {
        

        SizeF sf = grNew.MeasureString(text, new Font("Tahoma", fontSize));
        while (sf.Width > width)
        {
            fontSize--;
            sf = grNew.MeasureString(text, new Font("Tahoma", fontSize));
        }

        float x = (width - sf.Width) / 2;

        grNew.DrawString(text, new Font(new FontFamily("Tahoma"), fontSize,fs), new SolidBrush(cr) , new PointF(x, y));

    }


    /// <summary>
    /// this function will draw a text centered in a place on the image by a width
    /// </summary>
    /// <param name="grNew">the graphics to draw</param>
    /// <param name="fontSize">the font size</param>
    /// <param name="text">the text to draw</param>
    /// <param name="text2">the secound text to draw</param>
    /// <param name="y">the y position (no change)</param>
    /// <param name="width">the width to get x by</param>
    /// <param name="cr">this is the color of text to write</param>
    /// <param name="cr2">this the secound color for secound text</param>
    private void drawBadge(Graphics grNew, int fontSize, string text1,string text2, float y, float width, Color cr1,Color cr2)
    {


        SizeF sf = grNew.MeasureString(text1  + text2, new Font("Tahoma", fontSize));
        while (sf.Width > width)
        {
            fontSize--;
            sf = grNew.MeasureString(text1  + text2, new Font("Tahoma", fontSize));
        }

        float x = (width - sf.Width) / 2;

       



        grNew.DrawString(text1, new Font(new FontFamily("Tahoma"), fontSize,FontStyle.Italic), new SolidBrush(cr1), new PointF(x, y));
         sf = grNew.MeasureString(text1, new Font("Tahoma", fontSize));


         x = x + sf.Width;

         grNew.DrawString(text2, new Font("Tahoma", fontSize), new SolidBrush(cr2), new PointF(x, y));

    }



    /// <summary>
    /// this function will check the security and customize the page
    /// </summary>
    private void checkAndCustomizeSecurity()
    {
        mobjUser = GlobalVars.getCurrentPerson();

        if (!mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Registered_courses_page))
        {
            Response.Redirect("LoginEN.aspx");

        }

        checkID();

        if (!mobjUser.lstCourses.Contains(mobjFinishedExams.objRegisteredCourses.objCourses))
        {
            if (!mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Admin_page))
            {
                Response.Redirect("LoginEN.aspx");
            }
        }


        CertificateDataDB objCertificateDataDB = new CertificateDataDB(ConnectionStrings.LMS);

        List<CertificateData> lstCertificateData = objCertificateDataDB.Select("", "");

        if (lstCertificateData.Count == 0)
        {
            Response.Redirect("LoginEN.aspx");
        }

        mobjCertificateData = lstCertificateData[0];



    }


    /// <summary>
    /// this function will check the id from the request
    /// </summary>
    private void checkID()
    {
        if (Request["ID"] == null)
            Response.Redirect("LoginEN.aspx");

        long ExamID = -1;

        try { ExamID = long.Parse(Request["ID"]); }
        catch { Response.Redirect("LoginEN.aspx"); }

        FinishedExamsDB objFinishedExams = new FinishedExamsDB (ConnectionStrings.LMS);

        List<FinishedExams> lstFinished = objFinishedExams.Select("", " where [ID]='" + ExamID + "' AND [Degree] >= 75.0 ");
        if (lstFinished.Count == 0)
        {
            Response.Redirect("LoginEN.aspx");
        }

        mobjFinishedExams = lstFinished[0];
        
        

    }
}